package params

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
)

func ParamRoute(r gin.IRouter) {
	r.GET("/user/search", func(c *gin.Context) {
		//提取query参数
		username := c.Query("username")
		addr := c.Query("addr")

		c.JSON(200, gin.H{
			"username": username,
			"addr":     addr,
		})
	})

	r.POST("/user/search/post", func(c *gin.Context) {
		username := c.PostForm("username")
		addr := c.PostForm("addr")

		c.JSON(200, gin.H{
			"username": username,
			"addr":     addr,
		})
	})

	r.GET("/user/search/:username/:addr", func(c *gin.Context) {
		username := c.Param("username")
		addr := c.Param("addr")

		c.JSON(200, gin.H{
			"username": username,
			"addr":     addr,
		})
	})

	r.POST("/upload", func(c *gin.Context) {
		file, err := c.FormFile("file")
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"message": err.Error(),
			})
			return
		}
		if file == nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"message": "file null",
			})
			return
		}

		baseDir := "web/gin/upload/"
		baseFile, err := os.Open(baseDir)
		if os.IsNotExist(err) || baseFile == nil {
			fmt.Println("base dir not exists and create")
			os.MkdirAll(baseDir, 0755)
		}
		err = c.SaveUploadedFile(file, baseDir+file.Filename)
		if err != nil {
			c.JSON(200, gin.H{
				"message": "fail",
				"error":   err.Error(),
			})
			return
		}

		c.JSON(200, gin.H{
			"message": "ok",
		})
	})

	r.POST("/uploads", func(c *gin.Context) {
		form, _ := c.MultipartForm()
		a := form.Value["a"]
		fmt.Println(a)

		baseDir := "web/gin/upload/"
		baseFile, err := os.Open(baseDir)
		if os.IsNotExist(err) || baseFile == nil {
			fmt.Println("base dir not exists and create")
			os.MkdirAll(baseDir, 0755)
		}
		//文件
		files := form.File["file"]
		err = c.SaveUploadedFile(files[0], baseDir+files[0].Filename)
		if err != nil {
			c.JSON(200, gin.H{
				"message": "fail",
				"error":   err.Error(),
			})
			return
		}

		files1 := form.File["file1"]
		err = c.SaveUploadedFile(files1[0], baseDir+files1[0].Filename)
		if err != nil {
			c.JSON(200, gin.H{
				"message": "fail",
				"error":   err.Error(),
			})
			return
		}

		c.JSON(200, gin.H{
			"message": "ok",
		})
	})
}
